package uiLayer;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.InputMismatchException;
import java.util.Scanner;

import ctrLayer.GraphCtr;
import ctrLayer.PresetCtr;

public class GraphUI extends MenuUI{
	private Skeleton sk;
	private static boolean loaded = false;
	private boolean exit;
	private Menu menu;
	
	public GraphUI(){
		if(!loaded){
			PresetCtr pCtr = new PresetCtr();
			if(pCtr.saveExist()){
				try {
					pCtr.load();
					loaded = true;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		try{
			menu = new Menu("Graph UI", GraphUI.class);
			menu.add("Add Flavour To Graph", "addToGraph");
			menu.add("Remove Flavour From Graph", "removeFromGraph");
			menu.add("Show Graph", "showGraph");
			menu.add("Preset Settings", "showPresetUI");
			menu.add("Back", "back");
			GraphUIStart();
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	private void GraphUIStart() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		exit = false;
		while (!exit) {
			Method m = menu.run();
			if (m != null) {
				m.invoke(this, null);
			}
		}
	}
	
	private void back(){
		exit = true;
	}

	private void showGraph(){
		sk = Skeleton.getInstance();
		sk.setVisible(true);
	}
	
	private void addToGraph(){
		try{
			Scanner keyboard = new Scanner(System.in);
			clearConsole();
			System.out.println("*** Add To Graph ***");
			System.out.print("Flavour: ");
			String flavourName = keyboard.nextLine();
			GraphCtr gCtr = new GraphCtr();
			gCtr.addToGraph(flavourName);
			if(sk != null){
				 sk.reDraw();
			}else{
				showGraph();
			}
		}catch(InputMismatchException e){
			System.out.println("Invalid values");
			pause();
			return;
		}catch(NullPointerException e){
			System.out.println(e.getMessage());
			pause();
			return;
		}
	}
	
	private void removeFromGraph(){
		try{
			Scanner keyboard = new Scanner(System.in);
			clearConsole();
			System.out.println("*** Remove From Graph ***");
			System.out.print("Flavour: ");
			String flavourName = keyboard.nextLine();
			GraphCtr gCtr = new GraphCtr();
			gCtr.removeFromGraph(flavourName);
			if(sk != null){
				 sk.reDraw();
			}
		}catch(InputMismatchException e){
			System.out.println("Invalid values");
			pause();
			return;
		}
	}
	
	private void showPresetUI(){
		new PresetUI();
	}
}
